<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\coupon\Log;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\User as ModelUser;
use app\common\model\user\Address as userAddress;
use app\common\model\user\Withdrawal;
use DateTime;
use fast\Random;
use think\Config;
use think\Db;
use think\Log as ThinkLog;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['getWxMiniProgramSessionKey', 'wxLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 微信小程序登录
     *
     * @params string $openid 唯一标识
     * @params string $sessionKey 秘钥
     * @params string $iv 偏移量
     * @params string $encryptedData 加密串
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);

        // 入参
        if (empty($code) ||  empty($phoneCode)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid']
            ]);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession['openid'], $phoneCode);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!'.$this->auth->getError());
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo =  $this->auth->getUserinfo();

        $this->success('', compact('userInfo'));
    }
    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $post = $this->request->post();
        extract($post);
        if (isset($username) && $username) {
            // $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            // if ($exists) {
            //     $this->error(__('Username already exists'));
            // }
            $user->username = $username ?? '';
        }
        if (isset($avatar) && $avatar) {
            $user->avatar = $avatar ?? '';
        }
        if (isset($city) && $city) {
            $user->city = $city ?? '';
        }
        if (isset($mobile) && $mobile) {
            $user->mobile = $mobile ?? '';
        }
        if (isset($state) && $state) {
            $user->state = $state ?? '';
        }
        if (isset($clean) && $clean) {
            $user->clean = $clean ?? '';
        }
        $user->save();
        $this->success();
    }
    /**
     * 用户申请提现
     *
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = $this->auth->getUserinfo();
        extract($post);
        if (!isset($money) || empty($money)) {
            $this->error('提现金额不能为空');
        }
        if (!isset($bank_card_number) || empty($bank_card_number)) {
            $this->error('银行卡号不能为空');
        }
        if (!isset($name) || empty($name)) {
            $this->error('姓名不能为空');
        }
        if (!isset($bank) || empty($bank)) {
            $this->error('开户行不能为空');
        }
        // dd($user);
        if ($user['money'] < $money) {
            $this->error('余额不足');
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            $moneyLog = new MoneyLog();
            $moneyLog->income($user['id'], $money, 1, 500, $post['sn']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
 
    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;
        $data = userAddress::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = UserAddress::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function setDefaultAddress()
    {
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        UserAddress::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 获取用户添加收货地址
     *
     * @ApiMethod (GET)
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = UserAddress::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     */
    public function delAddress()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $data = UserAddress::delAddress($id, $uid);
        $this->success('删除成功', $data);
    }

    /**
     * 用户统计
     *
     */
    public function statistics()
    {
        $user_id = $this->auth->id;
        //更新过期优惠券
        Log::editState($user_id);
        $data['total']  = Order::where('user_id', $user_id)->whereNotIn('status', ['0', '-1'])->sum('total');
        $data['discount']  =  Order::where('user_id', $user_id)->whereNotIn('status', ['0', '-1'])->sum('discount_money');
        $data['coupon_num']  = Log::where('state', 1)->where('user_id', $user_id)->count();
        $this->success('', $data);
    }
    /**
     * 全部收款
     *
     */
    public function all_receipts()
    {
        $user_id = $this->auth->id;
        $moneyLog = new MoneyLog;
        $list = $moneyLog->where('type', '2')->where('user_id', $user_id)->distinct(true)->field("FROM_UNIXTIME(createtime,'%Y-%m') as date")->group('createtime')->paginate(10);
        foreach ($list as &$v) {
            $endDate = new DateTime($v['date']);
            $startDate = $endDate->format('Y-m-d');
            $endDate = $endDate->format('Y-m-t') . ' 23:59:59';
            $v['total_money'] = MoneyLog::where('type', '2')->where('user_id', $user_id)->where('createtime', 'between time', [$startDate, $endDate])->sum('money');
            $v['num'] = MoneyLog::where('type', '2')->where('user_id', $user_id)->where('createtime', 'between time', [$startDate, $endDate])->sum('num');
            $v['data']  = $moneyLog->getLists($v['date'], $user_id);
        }
        $this->success('', $list);
    }
}
